package zhoufu.sz.sanxiao_check.services;

import android.app.Activity;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.inject.Inject;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Streaming;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import zhoufu.sz.sanxiao_check.App;
import zhoufu.sz.sanxiao_check.R;
import zhoufu.sz.sanxiao_check.inject.components.AppComponent;
import zhoufu.sz.sanxiao_check.models.ApkInfo;
import zhoufu.sz.sanxiao_check.protocol.ApkInfoApi;
import zhoufu.sz.sanxiao_check.utils.StringConverterFactory;

/**
 * Created by toylu on 2015/12/6.
 */
public class DownloadService extends IntentService
{
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */

    public static final String Action_down_printApk = "Action_down_printAp";
    public static final String PATH                 = "http://120.31.131.105:8002";
    //public static final String PATH                 = "http://www.zf508.com";
    public static final String DOWNLOAD             = "DLEnforcement.apk";
    public static final String HOTFIX_DOWNLOAD      = "/apk/DLEnforcement.apk";
    public static final String PRINTAPK             = "print.apk";

    public static final String APKNAME       = "dl_sanxiao_checked_v2.apk";
    public static final String DOWNLOAD_INFO = "download_info";

    private File    fileAbsolutePath;
    private int     mTotal;
    private ApkInfo _apkInfo;

    @Inject
    App        _app;
    @Inject
    ApkInfoApi _apkInfoApi;
    private boolean      _isUpdateApp;
    private Subscription _getApkInfoSub;
    public static String APKINFONAME = "apkInfoName";

    public static void startDownLoadApk(Activity activity, String apkInfoAdd)
    {
        Intent intent = new Intent(activity, DownloadService.class);
        intent.putExtra(DownloadService.APKINFONAME, apkInfoAdd);
        activity.startService(intent);
    }

    public interface DownLoadHelper
    {
        @Streaming()
        @GET("apk/{apkName}")
        Call<ResponseBody> download(@Path("apkName") String apkName);

        @Streaming
        @GET(HOTFIX_DOWNLOAD)
        Observable<ResponseBody> downHotfix();
    }

    public DownloadService(String name)
    {
        super(name);
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        AppComponent.Instance.get().inject(this);
    }

    public DownloadService()
    {
        this("zhoufu.sz.sanxiao_check.services");
    }

    @Override
    protected void onHandleIntent(final Intent intent)
    {
        String apkInfoName = intent.getStringExtra(APKINFONAME);
        String string      = "apk";
        int    apk         = apkInfoName.indexOf("apk");
        String xmlurl      = apkInfoName.substring(0, apk + string.length() + 1);
        String apkName     = apkInfoName.substring(apk + string.length() + 1);
        _getApkInfoSub = getApkInfoApi(xmlurl).getAppInfo(apkName).subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ApkInfo>()
                {
                    @Override
                    public void onCompleted()
                    {

                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        System.out.println("e.getMessage() = " + e.getMessage());
                    }

                    @Override
                    public void onNext(ApkInfo apkInfo)
                    {
                        PackageManager packageManager = getApplication().getPackageManager();
                        // getPackageName()是你当前类的包名，0代表是获取版本信息
                        PackageInfo packInfo       = null;
                        int         appVersionCode = 1;
                        try
                        {
                            packInfo = packageManager
                                    .getPackageInfo(getApplication().getPackageName(), 0);
                            appVersionCode = packInfo.versionCode;
                        } catch (PackageManager.NameNotFoundException e)
                        {
                            e.printStackTrace();
                        }

                        //如果当前的版本较低
                        if ( apkInfo.getVersion() > appVersionCode )
                        {
                            //弹出更新框
                            _apkInfo = apkInfo;
                            //AlertDialog dialog=  new AlertDialog.Builder(DownloadService.this)
                            //          .setIcon(getResources().getDrawable(R.mipmap.ic_launcher))
                            //          .setPositiveButton(getResources().getText(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                            //              @Override
                            //              public void onClick(DialogInterface dialog, int which) {
                            //                  downLoad(intent);
                            //              }
                            //          }).setNegativeButton(getResources().getText(R.string.dialog_cancel),null).
                            //          setTitle("更新提示")
                            //          .create();
                            //  dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                            //  dialog.show();
                        }
                    }
                });
    }

    private ApkInfoApi getApkInfoApi(String xmlurl)
    {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(xmlurl)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(ApkInfoApi.class);
    }

    private void downLoad(Intent intent)
    {
        _apkInfo = intent.getParcelableExtra(DOWNLOAD_INFO);
        initNotifycation();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(PATH)
                .addConverterFactory(StringConverterFactory.create())
                .build();
        DownLoadHelper downLoadHelper = retrofit.create(DownLoadHelper.class);
        String         action         = intent.getAction();

        if ( TextUtils.equals(action, HOTFIX_DOWNLOAD) )
        {
            //下载 热补丁到 SDCARD中
            //            downHotfix(downLoadHelper);
        } else if ( TextUtils.equals(action, Action_down_printApk) )
        {
            downApk(downLoadHelper, PRINTAPK);
        } else
        {
            _isUpdateApp = true;
            downApk(downLoadHelper, DOWNLOAD);
        }
    }

    private void downApk(DownLoadHelper downLoadHelper, String apkName)
    {
        Call<ResponseBody> download = downLoadHelper.download(apkName);
        StringBuffer       name     = new StringBuffer();
        if ( Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) )
        {
            name.append(getExternalCacheDir().getAbsolutePath());
            name.append(File.separator);
            name.append("download");
            name.append(File.separator);
        } else
        {
            name.append(getCacheDir().getAbsolutePath());
            name.append(File.separator);
            name.append("download");
            name.append(File.separator);
        }

        String apkPath = name.toString();
        createDirs(apkPath);
        File file = new File(apkPath + apkName);
        //如果fileAbsolutePath 存在 且与要生成的file 相同 则打断新任务
        if ( null != fileAbsolutePath && TextUtils
                .equals(fileAbsolutePath.getPath(), file.getAbsolutePath()) )
        {
            return;
        }
        fileAbsolutePath = file.getAbsoluteFile();

        if ( file.exists() )
        {
            file.delete();
            file.length();
        }
        downFile(download, file);
    }


    private void downFile(Call<ResponseBody> download, File file)
    {

        FileOutputStream fos = null;
        InputStream      o   = null;
        try
        {
            Response<ResponseBody> execute = download.execute();
            o = execute.body().byteStream();
            file.createNewFile();
            byte[] buf  = new byte[2048];
            int    size = 0;
            mTotal = 0;
            fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            //mHandler.post(updateRunnable);
            while (( size = o.read(buf) ) != -1)
            {
                mTotal += size;
                bos.write(buf, 0, size);
                bos.flush();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            if ( fos != null )
            {
                try
                {
                    fos.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if ( o != null )
            {
                try
                {
                    o.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    private NotificationCompat.Builder mBuilder;
    private NotificationManager        mNotificationManager;

    private void initNotifycation()
    {
        mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("更新软件")
                .setContentText(_apkInfo.getAndroidcontent()).setDefaults(Notification
                        .FLAG_NO_CLEAR)
                .setProgress(_apkInfo.getAppbyte(), 0, false);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public void upDate()
    {
        // When the loop is finished, updates the notification
        if ( mTotal == _apkInfo.getAppbyte() )
        {
            //            long[] vibrate = {0,100,200};
            finished = true;
            mBuilder.setContentText("下载完成")
                    //Removes the progress bar
                    .setProgress(1, 1, false);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.setDataAndType(Uri.fromFile(fileAbsolutePath),
                    "application/vnd.android.package-archive");
            //            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            //            mBuilder.setContentIntent(pendingIntent);
            clearNotification();
            if ( _isUpdateApp )
            {
                _app.exit();
            }
        } else
        {

            mBuilder.setProgress(_apkInfo.getAppbyte(), mTotal, false);
        }
        mNotificationManager.notify(1, mBuilder.build());
    }

    private boolean finished;

    Runnable updateRunnable = new Runnable()
    {

        @Override
        public void run()
        {
            if ( !finished )
            {
                upDate();
                //mHandler.postDelayed(this, 1000);
            }
        }
    };

    //删除通知
    private void clearNotification()
    {
        // 启动后删除之前定义的通知
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }


    /**
     * 创建文件夹
     */
    public static boolean createDirs(String dirPath)
    {
        File file = new File(dirPath);
        if ( !file.exists() || !file.isDirectory() )
        {
            return file.mkdirs();
        }
        return true;
    }
}
